<template>
    <div class="tab-container-view">
        <a-tabs v-model="activeKey" :type="config.tabType" :tabPosition="config.tabPosition">
            <a-tab-pane v-for="(tabItem, index) in tabList" :key="tabItem.id">
                <span slot="tab">
                    <rx-use-icon v-if="tabItem.icon" v-model="tabItem.icon"></rx-use-icon>
                    {{ tabItem.name }}
                </span>
                <div class="tab-common">
                    <div class="tab-common-defConf" v-if="tabItem.defConf">
                        <div class="tab-common-button">
                            <span class="editBtnSpan" v-if="!cannotEdit.contains(tabItem.defConf)"
                                @click="setConfig(tabItem)"><a-icon :title="$ti18('rxList.editBtn', '编辑')"
                                    type="edit"></a-icon></span>
                            <span class="editBtnSpan" v-if="funcComponents.includes(tabItem.defConf)"
                                @click="copyAlias(tabItem)">
                                <a-icon :title="i18n('list.copyAlias', '复制标识')" type="key" />
                            </span>
                            <span class="editBtnSpan" v-if="funcComponents.includes(tabItem.defConf)"
                                @click="copyFunction(tabItem)">
                                <a-icon :title="i18n('list.copyFunction', '复制函数')" type="copy" />
                            </span>
                            <span class="editBtnSpan" v-if="tabItem.defConf == 'chart' && !tabItem.config"
                                @click="getChart(tabItem)">
                                <a-icon :title="i18n('list.importChart', '引入已有图表')" type="area-chart" />
                            </span>
                            <span class="btnSpan" @click="setDefConf(index, '')"><a-icon
                                    :title="$ti18('rxList.delBtn', '删除')" type="delete"></a-icon></span>
                        </div>
                        <tab-container-edit v-if="tabItem.defConf == 'tabContainer'" :ref="tabItem.config.name"
                            :layoutItem="tabItem" :config="tabItem.config" :editImgList="editImgList"
                            :paramConfig="paramConfig" :json="json"></tab-container-edit>
                        <customEditControl v-else :item="tabItem" :editImgList="editImgList" :readonly="false"
                            :paramConfig="paramConfig" :isDesign="true"></customEditControl>

                    </div>
                    <div class="tab-common-empty" v-else>
                        <a-button @click="addComponent(index)"><my-icon type="iconjia"></my-icon>添加组件</a-button>
                    </div>
                </div>
            </a-tab-pane>
        </a-tabs>
        <!--    编辑布局    -->
        <a-drawer placement="right" @close="close" width="550" :destroyOnClose="true" :visible="visible" :z-index="9999"
            :closable="false" :wrapClassName="'rxDrawerBox'" :bodyStyle="{ padding: 0 }">
            <customEditDef v-if="editTabItem.defConf" :support="editTabItem.defConf" :json="allControl"
                :supportConf="editTabItem.config" v-on:dragclick="dragClick" :portalLayout="false"
                :paramConfig="paramConfig" :mdl="mdl"></customEditDef>
        </a-drawer>
    </div>
</template>

<script>
/**
 * tab容器
 */
import { Util } from "@lowcode/jpaas-common-lib";
import insPortalDialog from "@/api/portal/core/insPortalDialog";
import CustomPageColumnDialog from "@/views/modules/portal/core/CustomPageColumnDialog";
import QuillEditorView from "@/views/modules/form/core/formComponent/QuillEditorView";
import FormChartComponentDialog from "@/views/modules/form/core/FormChartComponentDialog";
import TabContainerView from '@/views/modules/form/core/formComponent/TabContainerView.vue';
import FormChartBoard from "@/views/modules/form/core/FormChartBoard.vue";
import TabContainerOpen from "./TabContainerOpen.vue"

export default {
    name: "tab-container-edit",
    components: {
        "customEditControl": () => import('@/views/modules/form/core/FormCustomEditControl'),
        "customEditDef": () => import('@/views/modules/form/core/FormCustomEditDef'),
        "TabContainerEdit": () => import('@/views/modules/form/core/formComponent/TabContainerEdit'),
    },
    props: ["config", "editImgList", "paramConfig", "json",'mdl'],
    data() {
        return {
            activeKey: "1",
            tabList: [],
            //默认tab
            defTabs: [{ id: Util.randomId(), name: "Tab1", icon: "", defConf: "", config: "" }, { id: Util.randomId(), name: "Tab2", icon: "", defConf: "", config: "" }],
            visible: false,
            editTabItem: {},
            controlList: [],
            allControl: [],
            //需要拷贝脚本的组件
            funcComponents: ["form", "list", "tree", "chart", "custom", "bpm"],
            cannotEdit: ["column", "customColumn", "chartBoard", "myChartBoard"]
        }
    },
    created() {
        this.initConfig();
        if (this.json) {
            this.getAllControl(this.json);
        }
        if (this.tabList.length > 0) {
            this.activeKey = this.tabList[0].id;
        }
        this.getControlList();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formCustom", key);
        },
        i18n2(name, text, key) {
            return this.$ti18(name, text, "formComponent", key);
        },
        initConfig() {
            this.tabList = [];
            if (this.config && this.config.tabs) {
                this.tabList.push(...this.config.tabs);
            } else {
                this.tabList.push(...this.defTabs);
            }
        },
        getAllControl(controls) {
            for (let i = 0; i < controls.length; i++) {
                let control = controls[i];
                if (control.defConf == "tabContainer" && control.config.tabs && control.config.tabs.length > 0) {
                    this.getAllControl(control.config.tabs)
                } else {
                    this.allControl.push(control);
                }
            }
        },
        setDefConf(index, key) {
            this.config.tabs[index].defConf = key;
            if (key == 'tabContainer') {
                this.config.tabs[index].config = {
                    tabType: "line",
                    tabPosition: "top",
                    tabs: [{ id: Util.randomId(), name: "Tab1", icon: "", defConf: "", config: "" }, { id: Util.randomId(), name: "Tab2", icon: "", defConf: "", config: "" }]
                }
            } else if (key == 'chartBoard') {
                this.addChartBoard(index)
            } else {
                this.config.tabs[index].config = key == 'myChartBoard' ? {} : "";
            }
        },
        addChartBoard(index) {
            let self = this;
            Util.open({
                component: FormChartBoard,
                curVm: this,
                title: this.i18n('chartBoard', '图表看板'),
                max: false,
                widthHeight: ['400px', '600px'],
                data: {

                }
            }, function (action, data) {
                if (action != 'ok') return;
                self.config.tabs[index].config = data
                debugger
            });
        },
        setConfig(tabItem) {
            if (tabItem.defConf == "column") {
                this.addInsColumn(tabItem);
            } else if (tabItem.defConf == "customColumn") {
                this.addCustomColumn(tabItem);
            } else if (tabItem.defConf == "quillEditor") {
                Util.open({
                    component: QuillEditorView,
                    curVm: this,
                    title: this.i18n('list.richEditor', '富文本编辑器'),
                    max: true,
                    data: {
                        readOnly: false,
                        config: tabItem.config
                    }
                }, function (action, data) {
                    if (action != 'ok') return;
                    if (!tabItem.config) {
                        tabItem.config = { html: '' }
                    }
                    tabItem.config.html = data;
                });
            } else {
                this.editTabItem = tabItem;
                this.visible = true;
            }
        },
        close() {
            this.visible = false;
        },
        dragClick(config) {
            for (var i = 0; i < this.tabList.length; i++) {
                if (this.editTabItem.id == this.tabList[i].id) {
                    this.tabList[i].config = config;
                    break;
                }
            }
        },
        addInsColumn(tabItem) {
            let self = this;
            insPortalDialog.openInsCloumnDefDialog({
                curVm: this, data: { single: false }, widthHeight: ['800px', '600px']
            }, function (self_, columns) {
                for (let i = 0; i < columns.length; i++) {
                    var column = columns[i];
                    tabItem.config = { colId: column.colId, name: column.name }
                }
            });
        },
        addCustomColumn(tabItem) {
            var self = this;
            Util.open({
                component: CustomPageColumnDialog,
                curVm: this,
                title: self.i18n('list.customCol', '自定义页面栏目'),
                widthHeight: ['750px', '500px'],
            }, function (action, data) {
                if (action != 'ok') return;
                tabItem.config = { alias: data.alias, name: data.name }
            });
        },
        //复制标识
        copyAlias(item) {
            this.copyText("let component = this.getCustomViewComponent(\"" + item.id + "\",\"" + item.config.alias + "\");");
            this.$message.info(this.i18n2('tip.copySuccess', "复制了组件标识，你可以粘贴进行使用!"));
        },
        //复制函数
        copyFunction(item) {
            if (!item.config || !item.config.receive) {
                this.$message.warning(this.i18n2('tip.component', "该组件未配置传入参数，请去配置!"));
                return;
            }
            let params = {};
            //构造参数
            let mapping = [];
            //表单主键时需要取主键配置
            if (item.defConf == "form" && item.config.receive.isPk == "YES") {
                mapping = item.config.receive.pkMapping;
            } else {
                mapping = item.config.receive.mapping;
            }
            let ary = mapping.filter(item => {
                return item.valueSource == 'param';
            });
            for (let item of ary) {
                params[item.name] = "";
            }
            let paramsStr = JSON.stringify(params);
            let event = `var config = {
                //组件id
                component: "${item.id}",
                //传入参数
                params: ${paramsStr}
            };
            //触发页面定制公共事件函数
            this.$bus.emit('formCustomPublicEvent', config);`
            this.copyText(event);
            this.$message.info(this.i18n2('tip.successful', "生成发布事件成功,代码在剪切板中，你可以粘贴进行使用!"));
        },
        copyText(text) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text);
            } else {
                let textArea = document.querySelector("#temp_textarea");
                if (!textArea) {
                    textArea = document.createElement('textarea');
                    textArea.setAttribute("id", "temp_textarea");
                    // 使text area不在viewport，同时设置不可见
                    document.body.appendChild(textArea)
                }
                textArea.value = text;
                textArea.focus()
                textArea.select()
                // 执行复制命令并移除文本框
                document.execCommand('copy');
                textArea.remove();
            }
        },
        getChart(item) {
            Util.open({
                component: FormChartComponentDialog,
                curVm: this,
                title: this.i18n('importChart', '引入已有图表'),
                widthHeight: ['750px', '500px'],
            }, function (action, data) {
                if (action != 'ok' || !data.config) {
                    return;
                }
                item.config = JSON.parse(data.config);
                item.config.name = data.name;
            });
        },
        getControlList() {
            let exclude = ["quickEntrance"];
            for (let i = 0; i < this.editImgList.length; i++) {
                if (exclude.includes(this.editImgList[i].key)) {
                    continue;
                }
                this.controlList.push(this.editImgList[i]);
            }
        },
        /*
        添加组件
         */
        addComponent(index){
            let self = this;
            Util.open({
                component: TabContainerOpen,
                curVm: this,
                title: '添加组件',
                max: false,
                widthHeight: ['800px', '600px'],
                data: {
                    controlList:self.controlList,
                }
            }, function (action, data) {
                if (action != 'ok') return;
                self.setDefConf(index,data)
                debugger
            });
        },
    },
    watch: {
        config: {
            handler: function (val, oldval) {
                this.initConfig();
            },
            deep: true
        },
    },
}
</script>

<style scoped>
.tab-button{
    overflow: hidden;
    width: 260px;
    display: grid;
    justify-content: center;
    grid-gap:5px 5px;
    grid-template-columns: 1fr 1fr;
}
.tab-common {
    width: 100%;
    height: 100%;
    overflow: auto;
    padding: 10px;
}

.tab-common-empty {
    display: flex;
    height: 100%;
    width: 100%;
    align-items: center;
    justify-content: center;
}

.tab-common-defConf {
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;
}

.tab-common-button {
    display: none;
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 999;
}

.tab-container-view {
    width: 100%;
    height: 100%
}

.tab-container-view>>>.ant-tabs-right-content {
    height: 100%;
    padding-right: 1px !important;
}

.tab-container-view>>>.ant-tabs-bar {
    margin-bottom: 1px !important;
}

.tab-container-view>>>.ant-tabs-bottom-content {
    height: calc(100% - 50px);
}

.tab-container-view>>>.ant-tabs-bottom-bar {
    margin-top: 1px !important;
}

.tab-container-view>>>.ant-tabs-left-content {
    padding-left: 1px !important;
}

.btnSpan {
    border-radius: 15px;
    width: 30px;
    height: 30px;
    text-align: center;
    background: rgba(255, 88, 90, 0.85);
    display: inline-block;
    cursor: pointer;
    z-index: 99;
}

.btnSpan i {
    color: #fff;
    font-size: 16px;
    margin-top: 7px;
    text-align: center;
}

.btnSpan:hover {
    background: #f6393a;
}

.editBtnSpan {
    border-radius: 15px;
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    background: #5885ff;
    /* display: inline-block; */
    margin-right: 10px;
    cursor: pointer;
    z-index: 99;
    float: left;
}

.editBtnSpan i {
    color: #fff;
    font-size: 16px;
    margin-top: 7px;
    text-align: center;
}

.editBtnSpan:hover {
    background: #5885ff;
    transform: translate(0, -3px);
    transition: transform .5s;
}
</style>